package com.winit.openapi.apiadapter.controller.builder;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.winit.erp.spi.exception.ValidateException;
import com.winit.mms.spi.command.ItemForCustomerCommand;
import com.winit.mms.spi.command.ModifyProductForCustomerCommand;
import com.winit.mms.spi.vo.ItemForCustomerVO;
import com.winit.openapi.apiadapter.vo.ProductInformation;
import com.winit.openapi.constants.ErrorCode;
import com.winit.openapi.exception.ApiException;
import com.winit.openapi.util.APISysConfigUtil;
import com.winit.ups.spi.systemrule.CountryService;
import com.winit.ups.spi.systemrule.command.CountryCheckedCommand;
import com.winit.ups.spi.systemrule.vo.Country;

@Service("merchandiseBuilder")
public class MerchandiseBuilder {

    @Resource
    private CountryService   upsCountryService;

    @Resource
    private APISysConfigUtil apiSysConfigUtil;

    public ItemForCustomerCommand buildMerchandiseregister(JSONObject json) {
        ItemForCustomerCommand itemForCustomerCommand = new ItemForCustomerCommand();

        List<ItemForCustomerVO> itemForCustomerVOs = new ArrayList<ItemForCustomerVO>();
        ItemForCustomerVO itemForCustomerVO = null;

        JSONArray jsonList = json.getJSONArray("productList");

        for (int i = 0; i < jsonList.size(); i++) {
            JSONObject jo = (JSONObject) jsonList.get(i);
            itemForCustomerVO = new ItemForCustomerVO();
            itemForCustomerVO.setBrandName(jo.containsKey("brandedName") ? jo.getString("brandedName") : null);//
            itemForCustomerVO.setCnName(jo.getString("chineseName"));
            itemForCustomerVO.setDescription(jo.containsKey("remark") ? jo.getString("remark") : null);
            // MCountry mcountry = MCountry.getCountryByCodeOrName(ctx,
            // jo.getString("exportCountry"), null);

            String exportCountryStr = jo.getString("exportCountry");
            CountryCheckedCommand exportCountryCommand = new CountryCheckedCommand();
            exportCountryCommand.setCountryField(exportCountryStr);
            List<Country> countryList = upsCountryService.getCountryListByCodeOrName(exportCountryCommand);
            if (null == countryList || countryList.size() <= 0) {
                throw new ApiException(ErrorCode.MMS_EXPORT_COUNTRY_NOT_EXISTS_ERROR, exportCountryStr);
            }
            
            itemForCustomerVO.setExportCountryCode(countryList.get(0).getCountryCode());
            itemForCustomerVO.setExportCountryName(countryList.get(0).getCountryName());
            itemForCustomerVO.setExportDeclarePrice(jo.getString("exportDeclaredvalue"));
            itemForCustomerVO.setImportDeclarePrice(jo.getString("inportDeclaredvalue"));
            itemForCustomerVO.setInternetSite(jo.containsKey("displayPageUrl") ? jo.getString("displayPageUrl") : null);
            itemForCustomerVO.setIsFinance("N");
            itemForCustomerVO.setIsWithBattery(jo.getString("battery").toUpperCase());
            itemForCustomerVO.setIsWithBrand(jo.getString("branded").toUpperCase());
            itemForCustomerVO.setIsWithSocket("N");
            itemForCustomerVO.setRegisterHeight(jo.getString("registeredHeight"));
            itemForCustomerVO.setRegisterLength(jo.getString("registeredLength"));
            itemForCustomerVO.setRegisterWeight(jo.getString("registeredWeight"));
            itemForCustomerVO.setRegisterWidth(jo.getString("registeredWidth"));
            itemForCustomerVO.setModel(jo.getString("model"));
            itemForCustomerVO.setName(jo.getString("englishName"));
            itemForCustomerVO.setSkuCode(jo.getString("productCode"));
            itemForCustomerVO.setStockOutRate(jo.containsKey("stockOutRate") ? jo.getString("stockOutRate") : null);
            itemForCustomerVO.setLeadTime(jo.containsKey("leadTime") ? jo.getString("leadTime") : null);
            itemForCustomerVO.setReplenishmentLeadTime(jo.containsKey("rmentLeadTime") ? jo.getString("rmentLeadTime") : null);
            itemForCustomerVO.setSpecification(jo.containsKey("specification") ? jo.getString("specification") : null);
            // MCountry icountry = MCountry.getCountryByCodeOrName(ctx,
            // jo.getString("inporCountry"), null);
            // 校验进口国
            String importCountryStr = jo.getString("inporCountry");
            String value = apiSysConfigUtil.getConfigValueByKey("API_MMS_REGISTER_PRODUCT_IMPORT_COUNTRY_LIST");
            if (StringUtils.isBlank(value)) {
                value = "AU,UK,US,DE,BE,PL,NL";
            }
            String[] countryArray = value.split("\\,");
            List<String> countryCodeList = Arrays.asList(countryArray);
            // 限制进口国必须是AU,UK,US,DE,BE
            if (!countryCodeList.contains(importCountryStr)) {
                throw new ValidateException(ErrorCode.MMS_IMPORT_COUNTRY_NOT_SUPPORT_ERROR, value);
            }
            
            CountryCheckedCommand importCountryCommand = new CountryCheckedCommand();
            importCountryCommand.setCountryField(importCountryStr);
            List<Country> importCountryList = upsCountryService.getCountryListByCodeOrName(importCountryCommand);
            if (null == importCountryList || importCountryList.size() <= 0) {
                throw new ApiException(ErrorCode.MMS_IMPORT_COUNTRY_NOT_EXISTS_ERROR, importCountryStr);
            }
//            Country importCountry = upsCountryService.getCountryByCodeOrName(importCountryStr);
//            if (importCountry == null) {
//                throw new ApiException(ErrorCode.MMS_IMPORT_COUNTRY_NOT_EXISTS_ERROR, importCountryStr);
//            }
            itemForCustomerVO.setImportCountryCode(importCountryList.get(0).getCountryCode());
            itemForCustomerVO.setImportCountryName(importCountryList.get(0).getCountryName());
            itemForCustomerVO.setImportDeclarePrice(jo.getString("inportDeclaredvalue"));

            itemForCustomerVOs.add(itemForCustomerVO);

        }
        itemForCustomerCommand.setProductList(itemForCustomerVOs);

        return itemForCustomerCommand;

    }

    public List<Map<String, Object>> buildRegisterResult(JSONObject json) {

        List<Map<String, Object>> data = new ArrayList<Map<String, Object>>();

        JSONArray jsonList = json.getJSONArray("productList");

        for (int i = 0; i < jsonList.size(); i++) {
            JSONObject jo = (JSONObject) jsonList.get(i);
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("productCode", jo.getString("productCode"));
            data.add(map);
        }

        return data;
    }

    public ModifyProductForCustomerCommand buildMerchandiseUpdate(JSONObject json) {
        ProductInformation productInfo = JSONObject.toJavaObject(json, ProductInformation.class);

        ModifyProductForCustomerCommand command = new ModifyProductForCustomerCommand();
        command.setBrandName(productInfo.getBrandedName());//
        command.setCnName(productInfo.getChineseName());
        command.setDescription(productInfo.getRemark());
        // TODO 开发者编辑没有进出口国以及价值
        command.setInternetSite(productInfo.getDisplayPageUrl());
        command.setIsFinance("N");
        if (productInfo.getBattery() != null) {
            command.setIsWithBattery(productInfo.getBattery().toUpperCase());
        }
        if (productInfo.getBrand() != null) {
            command.setIsWithBrand(productInfo.getBrand().toUpperCase());
        }
        command.setIsWithSocket("N");
        if (productInfo.getRegisteredHeight() != null) {
            command.setRegisterHeight(productInfo.getRegisteredHeight().toString());
        }
        if (productInfo.getRegisteredLength() != null) {
            command.setRegisterLength(productInfo.getRegisteredLength().toString());
        }
        if (productInfo.getRegisteredWeight() != null) {
            command.setRegisterWeight(productInfo.getRegisteredWeight().toString());
        }
        if (productInfo.getRegisteredWidth() != null) {
            command.setRegisterWidth(productInfo.getRegisteredWidth().toString());
        }
        command.setModel(productInfo.getModel());
        command.setName(productInfo.getEnglishName());
        command.setSkuCode(productInfo.getProductCode());
        command.setSpecification(productInfo.getSpecification());
        command.setImportCountryCode(productInfo.getState());
        if (productInfo.getStockOutRate() != null) {
            command.setStockOutRate(productInfo.getStockOutRate().toString());
        }
        if (productInfo.getLeadTime() != null) {
            command.setLeadTime(productInfo.getLeadTime().toString());
        }
        if (productInfo.getRmentLeadTime() != null) {
            command.setReplenishmentLeadTime(productInfo.getRmentLeadTime().toString());
        }

        if (productInfo.getStockOutRate() != null) {
            command.setStockOutRate(productInfo.getStockOutRate().toString());
        }
        if (productInfo.getLeadTime() != null) {
            command.setLeadTime(productInfo.getLeadTime().toString());
        }
        if (productInfo.getRmentLeadTime() != null) {
            command.setReplenishmentLeadTime(productInfo.getRmentLeadTime().toString());
        }

        return command;
    }

}
